import * as Employee from '@/api/system'
import { VueCropper } from 'vue-cropper'
export default {
  components: { VueCropper },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      formRules: {
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        graduationSchool: [{ required: false, message: '请输入毕业院校', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        education: [{ required: false, message: '请选择学历', trigger: 'change' }],
        departmentId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
        roleId: [{ required: true, message: '请选择职位', trigger: 'change' }],
        isTeacher: [{ required: true, message: '请选择身份', trigger: 'change' }],
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        label: [{ required: true, message: '请输入标签', trigger: 'blur' }],
        experiences: [{ required: true, message: '请输入教育经历', trigger: 'blur' }],
        jobs: [{ required: true, message: '请输入工作经历', trigger: 'blur' }],
        teachingType: [{ required: true, message: '请选择教学类型', trigger: 'change' }],
        workNo: [{ required: true, message: '工号不能为空', trigger: 'blur' },{ type: 'number', message: '工号必须为数字', trigger: 'blur' }],
        teachingTime: [{ required: true,message: '请选择从教时间',trigger: 'blur' }],
        subjectType: [{ required: true, message: '请选择授课类型', trigger: 'change' }],
        subjectArray: [ { required: true, message: '请选择授课类型', trigger: 'change' }],
        trait: [{ required: true, message: '请输入教学特点', trigger: 'blur' }],
        score: [{ required: true, message: '请输入教学成果', trigger: 'blur' }],
        grades: [{ type:'array', required: true,message: '请选择年级',trigger: 'change' }]
      },
      isShowDialog: false,
      hideUpload: false,// 上传相片选中框
      isLoading: false,// 防止重复提交
      showInfo: '',// 密码不可修改
      isEdit: false,// 不可编辑
      imgsList: [],// 头像
      momentList: [],// 教师风采
      certificateList: [],// 奖项证书
      positionAllList: [],// 职位列表
      departmentAllList: [],// 部门列表
      grades: [],// 年级
      interestCourseList: [],// 授课类型
      subjectTypeList: [],// 授课类型
      gradesList: [],// 授课年级
      momentFile: null,
      imgFile: null,
      stytleArr: [],
      certificatesArr: [],
      // 裁剪设置
      cropper: {
        dialog: false,
        // src:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg",
        width: 172 * 3,
        height: 208 * 3,
        aspectRatio: 1,
        fileBlob: {}
      },
      // 裁剪组件的基础配置option
      option: {
        mode: 'cover', // 图片默认渲染方式
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 172 * 3, // 默认生成截图框宽度
        autoCropHeight: 208 * 3, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [172, 208], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      }
    }
  },
  methods: {
    // 确定裁剪后获取截图的blob数据
    confirmCropper() {
      this.$refs.cropper.getCropBlob((data) => {
        const raw = {
          raw: data,
          name: new Date().valueOf()
        }
        this.uploadImgToOss(raw, true)
          .then((response) => {
            this.form.avatar = response.imgUrl
            this.imgsList = [{ url: response.imgUrl }]
            this.hideUpload = true
          })
          .finally(() => {
            this.cropper.dialog = false
          })
      })
    },
    // upload上传图片时触发
    handleAvatar(res, fileList) {
      // console.log(res)
      this.cropper.dialog = true
      this.option.img = URL.createObjectURL(res.file)
    },
    // 上传文件之前的钩子 若返回false或者Promise则停止上传
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /**
     *  图片上传||移除
     *  头像
     *  资质
     *  风采
     */
    handleRemove(file, fileList) {
      this.cropper.dialog = false
      this.hideUpload = false;
      this.imgsList = []
      this.form.avatar = ''
    },
    handleChange(file, fileList) {
      this.cropper.dialog = true
      this.option.img = file.url
      this.imgFile = fileList.length > 0 ? file : null
      this.hideUpload = fileList.length >= 1
    },
    // -----------------------教师风采---------------------------------------------
    handleRemovemomentList(file, fileList) {
      const arr = []
      console.log(file);
      this.form.styles.split(',').forEach((item, index) => {
        if (item !== file['url']) {
          arr.push(item)
        }
      })
      this.form.styles = arr.join(',')
      this.momentFile = null
    },
    handleChangemomentList(file, fileList) {
      this.momentFile = fileList.length >= 1 ? file : null
      this.uploadImgToOss(this.momentFile).then((response) => {
        if(!this.form.styles){
          this.form.styles = response['imgUrl']
        }else{
          this.form.styles = this.form.styles + ','+ response['imgUrl']
        }
      })
    },
    // -----------------------奖项证书---------------------------------------------
    handleRemovecertificateList(file, fileList) {
      const arr = []
      console.log(this.form.certificates);
      this.form.certificates.split(',').forEach((item, index) => {
        if (item !== file['url']) {
          arr.push(item)
        }
      })
      this.form.certificates = arr.join(',')
      this.certificateFile = null
    },
    handleChangecertificateList(file, fileList) {
      this.certificateFile = fileList.length >= 1 ? file : null
      this.uploadImgToOss(this.certificateFile).then((response) => {
        if(!this.form.certificates){
          this.form.certificates = response['imgUrl']
        }else{
          this.form.certificates = this.form.certificates + ','+ response['imgUrl']
        }
      })
    },
    // -----------------------列表数据请求---------------------------------------------
    getPositionAllList() {
      Employee.organizePostionList({
        orgId: this.$store.getters.businessId
      }).then((response) => {
        this.positionAllList = response.data
      })
    },
    getGradesList() {
      Employee.gradesList().then((res) => {
        res.data.forEach((item) => {
          item.gradeList.forEach((v, i) => {
            this.gradesList.push(v)
            this.gradesList = JSON.parse(JSON.stringify(this.gradesList))
          })
        })
      })
    },
    getDepartmentAllList() {
      Employee.organizeAllDepartment({
        orgId: this.$store.getters.businessId
      }).then((response) => {
        this.departmentAllList = response.data
      })
    },
    getSubjectList() {
      Employee.subjectList().then((res) => {
        this.subjectTypeList = res.data
        this.subjectTypeList.forEach((item, index) => {
          if (item.name.indexOf('学科辅导') !== -1) {
            this.interestCourseList = item.categories
          }
        })
      })
    },
    getAllList() {
      return new Promise((resolve, reject) => {
        Employee.organizeEmployeeList({
          currentPage: 1,
          pageSize: 2000,
          orgId: this.$store.getters.businessId
        }).then((response) => {
          this.validateRepeatArray = response.data.data
          resolve(response.data.data)
        })
      })
    },    
    validRepeatWorkNum() {
      this.getAllList().then((res) => {
        this.isRegister = null
        if (this.form.workNo == '') return
        const repeatValidateArray = []
        for (const value of res) {
          repeatValidateArray.push(value['workNo'])
        }
        this.isRegister = repeatValidateArray.indexOf(this.form.workNo)
      })
    },
    validReoeatPhoneNum() {
      if (this.form.isPhoneNum === '') return
      Employee.isRepeatPhoneNum({ phone: this.form.phone }).then((res) => {
        if (this.form.phone.length !== 11) {
          this.isPhoneNum = null
          return
        }
        this.isPhoneNum = res.data.exist == 1 ? 2 : 1
      })
    },    
    // 获取列表数据
    getAllOptionsList() {
      this.getDepartmentAllList()
      this.getPositionAllList()
      this.getSubjectList()
      this.getGradesList()
    },
    // 启用或禁用
    handleStatus(row, index) {
      const tips = row.adminStatus === 1 ? '禁用' : '启用'
      const confirmObj = {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      this.$confirm(`是否确认${tips}该员工？`, '提示', confirmObj).then(() => {
        Employee.organizeEmployeeStatus({
          id: row['userId'],
          status: 1 - row.adminStatus
        }).then((response) => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list[index]['adminStatus'] = 1 - row.adminStatus
        })
      })
    },
    // 删除员工
    handleDelete(row, index) {
      const tipsObj = {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      this.$confirm('是否确认删除该员工？', '提示', tipsObj).then(() => {
        Employee.organizeEmployeeDelete({
          id: row['userId']
        }).then((response) => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    },
  }
}

